<template>
  <div class="page-container">
    <div class="container">
  <el-container style="height: 100%;">
    <el-header>
      <h3>我的打卡记录</h3>
    </el-header>
    <el-main>
      <el-table :data="sortedAttendanceRecords" style="width: 100%" v-loading="loading">
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="attendanceStatus" label="打卡状态"></el-table-column>
        <el-table-column prop="clockTime" label="打卡时间">
          <template #default="scope">
            <span>{{ formatDate(scope.row.clockTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="clockInType" label="打卡类型"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="text" @click="clockIn(scope.row)" v-if="scope.row.attendanceStatus === '未打卡'">打卡</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          prev-text="←旧👈"
          next-text="👉新→"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px;"
      ></el-pagination>
    </el-main>
  </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const attendanceRecords = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
const sortedAttendanceRecords = computed(() => {
  return [...attendanceRecords.value].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
});

const fetchAttendanceRecords = async (page = 1, size = 10, isInitialLoad = false) => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:8080/users/attendance', {
      params: {
        employeeId: userInfo.employeeId,
        page: page,
        size: size
      }
    });
    if (response.data) {
      attendanceRecords.value = response.data.records;
      total.value = response.data.total;

      if (isInitialLoad) {
        const totalPages = Math.ceil(total.value / size);
        currentPage.value = totalPages;
        await fetchAttendanceRecords(totalPages, size);
      }
    } else {
      ElMessage.error('获取打卡记录失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
  } finally {
    loading.value = false;
  }
};

const clockIn = async (record) => {
  try {
    const response = await axios.post('http://localhost:8080/users/clock-in', {
      attendanceId: record.id
    });
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      // 更新当前记录的状态
      record.attendanceStatus = '已打卡';
    } else {
      ElMessage.error('打卡失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchAttendanceRecords(currentPage.value, newSize);
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchAttendanceRecords(newPage, pageSize.value);
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(d.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(d.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(d.getSeconds()).padStart(2, '0'); // 秒补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
  fetchAttendanceRecords(1, pageSize.value, true); // 初始加载时传入 true
});
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>